<template>
  <div style="height:100%;background-color:#f5f5f5">
    <van-nav-bar title="搜索" left-text="返回" @click-left="onClickLeft" left-arrow :style="rgba[0]" />
    <van-search shape="round" v-model="value" placeholder="请输入搜索关键词" @search="onSearch" />
    <div class="sear_all">
      <div class="sear">
        <p>搜索历史</p>
        <template v-if="arrs.length==0">
          <div class="p1">历史记录空空如也</div>
        </template>
        <template v-else>
          <div v-for="(items,j) of arrs" :key="j" class="record" @click="fn(items)">{{items}}</div>
        </template>
      </div>
      <div class="sear">
        <p>热门搜索</p>
        <div v-for="(item,i) of arr" :key="i" class="record" @click="fn(item)">{{item}}</div>
      </div>
    </div>
  </div>
</template>

<script>
//搜素页
import Vue from "vue";
import { Toast } from "vant";
import { Search } from "vant";

Vue.use(Search);
Vue.use(Toast);
export default {
  name: "search",
  data() {
    return {
      rgba: {},
      value: "", //输入的内容
      arrs: [], //搜索历史
      arr: ["计算机二级", "英语", "人工智能", "区块链"] //热门搜索
    };
  },
  created() {
    this.rgba = JSON.parse(localStorage.getItem("bakcColor") || []);
    // this.arrs = JSON.parse(localStorage.getItem("record") || []);
    this.local()
  },
  methods: {
    onClickLeft() {
      //退回上一个
      this.$router.go(-1);
    },
    local(){//解决localStorage一开始没数据的情况
      let rea = localStorage.getItem("record");
      if(rea!==null){
        this.arrs = JSON.parse(localStorage.getItem("record") || []);
      }
      // if(rea){}
    },
    fn(vals) {
      //历史+热门
      this.onSearch(vals);
    },
    onSearch(val) {
      //回车
      if (val == "") {
        return;
      } else {
        this.arrs.push(val);
        localStorage.setItem("record", JSON.stringify(this.arrs));
        this.allqu(val);
      }
    },
    allqu(val) {
      //查找题库
      let data = JSON.parse(localStorage.getItem("datas"));
      let arrId = [];
      for (let item of data.all_quiz_list) {
        if (item.subject == val) {
          arrId.push(item.quiz_list_id);
        }
      }
      if (arrId.length > 0) {
        //查找正确
        this.$router.push({ path: "/choice", query: { arrId: arrId } });
      } else {
        Toast.fail("暂无更多数据");
      }
    }
  },
  watch: {}
};
</script>

<style lang="scss" scoped>
@import "@/style/search/search.scss";
</style>